package com.gitee.ywj1352.算法.week01;

public class 二分法 {



    int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1; // 注意

        while(left <= right) { // 注意
            int mid = (right + left) / 2;
            if(nums[mid] == target)
                return mid;
            else if (nums[mid] < target)
                left = mid + 1; // 注意
            else if (nums[mid] > target)
                right = mid - 1; // 注意
        }
        return -1;
    }



    int erfen(int[] nums, int target){
        int l = 0 , r = nums.length - 1 , mid;
        while (l <= r){
            mid = (l+r)/2;

            if (nums[mid] == target){
                return mid;
            }else if(nums[mid] > target){
                l = mid +1;
            }else if(nums[mid] < target){
                r = mid -1;
            }
        }
        return  -1;
    }

    int erfenl(int[] nums, int target){
        int l = 0 , r = nums.length , mid;
        while (l < r){
            mid = (l+r)/2;

            if (nums[mid] == target){
                r =  mid;
            }else if(nums[mid] > target){
                l = mid +1;
            }else if(nums[mid] < target){
                r = mid ;
            }
        }
        return  l;
    }
    int left_bound(int[] nums, int target) {
        if (nums.length == 0) return -1;
        int left = 0;
        int right = nums.length; // 注意
        while (left < right) { // 注意
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                right = mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid; // 注意
            }
        }
        return left;
    }


    int right_bound(int[] nums, int target) {
        if (nums.length == 0) return -1;
        int left = 0, right = nums.length;

        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                left = mid + 1; // 注意
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid;
            }
        }
        return left - 1; // 注意
    }




}
